package com.github.ylt.protocol.http;

import com.github.ylt.utils.XmlUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;
import lombok.SneakyThrows;

import java.io.File;
import java.io.RandomAccessFile;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Objects;

/**
 * @author wutong
 */
public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println(cause.getMessage());
    }

    private void handleResource(ChannelHandlerContext ctx, HttpRequest request, URL resource) throws Exception {
        URI uri = Objects.requireNonNull(resource).toURI();
        File file1 = new File(uri.getPath());
        try (RandomAccessFile file = new RandomAccessFile(file1, "r")) {
            long length = file.length();
            byte[] bytes = new byte[(int)length];
            file.read(bytes,0,(int)length);
            ByteBuf content = Unpooled.copiedBuffer(bytes);
            DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,content);
            response.setProtocolVersion(request.protocolVersion());
            response.setStatus(HttpResponseStatus.OK);
            response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/xml;charset=utf-8");
            response.headers().set(HttpHeaderNames.ALLOW,"GET, HEAD, POST, SUBSCRIBE, UNSUBSCRIBE");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH,length+"");
            response.headers().set(HttpHeaderNames.SERVER,new String("ubuntu/22.04 UPnP/1.0 我是你爹/1.0".getBytes(), StandardCharsets.UTF_8));
            if (!file1.exists() || file1.isHidden()) {
                response.setStatus(HttpResponseStatus.NOT_FOUND);
                response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
                response.headers().set(HttpHeaderNames.CONTENT_LENGTH,"未找到！！！".length()+"");
                ctx.writeAndFlush("未找到！！！");
                return;
            }
            ctx.writeAndFlush(response);
        }
    }

    private Map<String,Object> getParams(){
        return null;
    }

    @SneakyThrows
    private void actions(String action, FullHttpRequest request, DefaultFullHttpResponse response, ChannelHandlerContext ctx){
        if("SetAVTransportURI".equals(action)){
            String string = request.content().toString(StandardCharsets.UTF_8);
            System.out.println(string);
            Map<String, Object> parse = XmlUtils.getInstance().parse(string);
            response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH,0+"");
            ctx.writeAndFlush(response);
            return;
        }
        if("GetTransportInfo".equals(action)){

        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        if(msg instanceof HttpRequest httpRequest){
            URI uri = new URI(httpRequest.uri());
            if("/AVTransport/action".equals(uri.getPath())){
                if(ReferenceCountUtil.refCnt(msg) == 1){
                    ReferenceCountUtil.retain(msg);
                }
                ctx.fireChannelRead(msg);
                return;
            }
            if("/favicon.ico".equals(uri.getPath())){
                return;
            }

            if("/".equals(uri.getPath())){
                ByteBuf content= Unpooled.copiedBuffer("hello world", CharsetUtil.UTF_8);
                DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,content);
                response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
                response.headers().set(HttpHeaderNames.CONTENT_LENGTH,content.readableBytes()+"");
                ctx.writeAndFlush(response);
                return;
            }
            if ("/description.xml".equals(uri.getPath())){
                URL resource = HttpServerHandler.class.getResource("/xml/description.xml");
                handleResource(ctx,httpRequest,resource);
                return;
            }
            if ("/dlna/AVTransport.xml".equals(uri.getPath())){
                URL resource = HttpServerHandler.class.getResource("/xml/AVTransport.xml");
                handleResource(ctx,httpRequest,resource);
                return;
            }
            if ("/dlna/RenderingControl.xml".equals(uri.getPath())){
                URL resource = HttpServerHandler.class.getResource("/xml/RenderingControl.xml");
                handleResource(ctx,httpRequest,resource);
                return;
            }
            if ("/dlna/ConnectionManager.xml".equals(uri.getPath())){
                URL resource = HttpServerHandler.class.getResource("/xml/ConnectionManager.xml");
                handleResource(ctx,httpRequest,resource);
            }
        }
    }
}
